package com.atguigu.crowd.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.atguigu.crowd.entity.po.MemberConfirmInfoPO;
import com.atguigu.crowd.entity.po.MemberLaunchInfoPO;
import com.atguigu.crowd.entity.po.ProjectPO;
import com.atguigu.crowd.entity.po.ReturnPO;
import com.atguigu.crowd.entity.vo.DetailProjectVO;
import com.atguigu.crowd.entity.vo.MemberConfirmInfoVO;
import com.atguigu.crowd.entity.vo.MemberLauchInfoVO;
import com.atguigu.crowd.entity.vo.PortalProjectVO;
import com.atguigu.crowd.entity.vo.PortalTypeVO;
import com.atguigu.crowd.entity.vo.ProjectVO;
import com.atguigu.crowd.entity.vo.ReturnVO;
import com.atguigu.crowd.entity.vo.TagVO;
import com.atguigu.crowd.entity.vo.TypeVO;
import com.atguigu.crowd.mapper.MemberConfirmInfoPOMapper;
import com.atguigu.crowd.mapper.MemberLaunchInfoPOMapper;
import com.atguigu.crowd.mapper.ProjectItemPicPOMapper;
import com.atguigu.crowd.mapper.ProjectPOMapper;
import com.atguigu.crowd.mapper.ReturnPOMapper;
import com.atguigu.crowd.mapper.TagPOMapper;
import com.atguigu.crowd.mapper.TypePOMapper;
import com.atguigu.crowd.service.api.ProjectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Transactional(readOnly = true)
@Service
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	private ReturnPOMapper returnPOMapper;
	
	@Autowired
	private MemberConfirmInfoPOMapper memberConfirmInfoPOMapper;
	
	@Autowired
	private MemberLaunchInfoPOMapper memberLaunchInfoPOMapper;
	
	@Autowired
	private ProjectPOMapper projectPOMapper;
	
	@Autowired
	private ProjectItemPicPOMapper projectItemPicPOMapper;
	
	@Autowired
	private TypePOMapper typePOMapper;
	
	@Autowired
	private TagPOMapper tagPOMapper;
	
	
	
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
	@Override
	public void saveProject(ProjectVO projectVO, Integer memberId) {
		
		//一：保存项目发起人信息,需要memberID
		//需要保存发起人的外键id
		MemberLauchInfoVO memberLauchInfoVO = projectVO.getMemberLauchInfoVO();
		MemberLaunchInfoPO memberLaunchInfoPO = new MemberLaunchInfoPO();
		BeanUtils.copyProperties(memberLauchInfoVO, memberLaunchInfoPO);
		//设置memberid
		memberLaunchInfoPO.setMemberid(memberId);
		memberLaunchInfoPOMapper.insert(memberLaunchInfoPO);
		
		//获取项目的发起人外键，避免外键约束导致插入数据失败
		//需要在mapper.xml中设置useGeneratedKeys="true" keyProperty="id"
		Integer launchId = memberLaunchInfoPO.getId();
		
		//二：保存projectPO对象
		ProjectPO projectPO = new ProjectPO();
		projectPO.setMoney(projectVO.getMoney().longValue());
		BeanUtils.copyProperties(projectVO, projectPO);
		//设置属性
		
		projectPO.setMemberid(memberId);
		String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		projectPO.setCreatedate(date);
		projectPO.setDeploydate(date);
		projectPO.setStatus(1);//代表项目众筹即将开始
		//projectPOMapper.insertSelective(projectPO);
	
		//保存项目发起人外键
		projectPO.setLaunchid(launchId);
		//保存项目
		projectPOMapper.insertSelective(projectPO);
		
		//获取项目ID外键，避免外键约束导致插入数据失败
		//需要在mapper.xml中设置useGeneratedKeys="true" keyProperty="id"
		Integer projectId = projectPO.getId();
		
		//二：保存项目、分类关系中间表，需要projectID
		List<Integer> typeIdList = projectVO.getTypeIdList();
		projectPOMapper.insertTypeRelationship(typeIdList, projectId);
		
		//三：保存项目、标签关系中间列表，需要projectID
		List<Integer> tagIdList = projectVO.getTagIdList();
		projectPOMapper.insertTagRelationship(tagIdList, projectId);
		
		//四：保存详情图片，需要projectID
		List<String> detailPicturePathList = projectVO.getDetailPicturePathList();
		projectItemPicPOMapper.insertPathList(detailPicturePathList,projectId);
		
		
		
		//六：保存项目回报信息,需要projectID和launchId
		List<ReturnVO> returnVOList = projectVO.getReturnVOList();
		List<ReturnPO> returnPOList = new ArrayList<ReturnPO>();
		for (ReturnVO returnVO : returnVOList) {
			ReturnPO returnPO = new ReturnPO();
			BeanUtils.copyProperties(returnVO, returnPO);
			returnPOList.add(returnPO);
			
		}
		returnPOMapper.insertReturnPOBatch(returnPOList,projectId,launchId);
		
		//七：保存项目确认信息,需要memberID
		MemberConfirmInfoVO memberConfirmInfoVO = projectVO.getMemberConfirmInfoVO();
		MemberConfirmInfoPO memberConfirmInfoPO = new MemberConfirmInfoPO();
		BeanUtils.copyProperties(memberConfirmInfoVO, memberConfirmInfoPO);
		//设置memberID
		memberConfirmInfoPO.setMemberid(memberId);
		memberConfirmInfoPOMapper.insert(memberConfirmInfoPO);
		
		
	}

	@Override
	public List<PortalTypeVO> getPortalTypeVOList() {
		return projectPOMapper.selectPortalTypeVOList();
	}

	@Override
	public DetailProjectVO getDetailProjectVO(Integer projectId) {
		//获取项目详情对象
		DetailProjectVO detailProjectVO = projectPOMapper.selectDetailProjectVO(projectId);
		
		//设置剩余天数
		String deployDate = detailProjectVO.getDeployDate();
		Date currentDate = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date deployDay = format.parse(deployDate);
			
			// 获取当前当前日期的时间戳
			long currentTimeStamp = currentDate.getTime();
			
			// 获取众筹日期的时间戳
			long deployTimeStamp = deployDay.getTime();
			
			// 两个时间戳相减计算当前已经过去的时间
			long pastDays = (currentTimeStamp - deployTimeStamp) / 1000 / 60 / 60 / 24;
			
			// 获取总的众筹天数
			Integer totalDays = detailProjectVO.getDay();
			
			// 使用总的众筹天数减去已经过去的天数得到剩余天数
			Integer lastDay = (int) (totalDays - pastDays);
			if (lastDay<=0) {
				lastDay = 0;
				Integer money = detailProjectVO.getMoney();
				Integer supportMoney = detailProjectVO.getSupportMoney();
				if(money>supportMoney) {//若筹集天数结束，筹集金额小于目标金额，则设置众筹状态为众筹失败
					detailProjectVO.setStatusText("已关闭");
				}else {
					detailProjectVO.setStatusText("众筹成功");
				}
			}
			detailProjectVO.setLastDay(lastDay);
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//设置众筹状态
		Integer status = detailProjectVO.getStatus();
		switch(status) {
			case 0:
				detailProjectVO.setStatusText("审核中");
				break;
			case 1:
				detailProjectVO.setStatusText("众筹中");
				break;
			case 2:
				detailProjectVO.setStatusText("众筹成功");
				break;
			case 3:
				detailProjectVO.setStatusText("已关闭");
				break;
			default:
				break;
		}
		return detailProjectVO;
	}

	@Override
	public MemberLauchInfoVO getLaunchInfoVO(Integer projectId) {
		//获取项目详情对象
		MemberLauchInfoVO memberLauchInfoVO = memberLaunchInfoPOMapper.selectLaunchInfo(projectId);
		//设置认证状态
		// 0 - 未实名认证， 1 - 实名认证申请中， 2 - 已实名认证
		Integer status = memberLauchInfoVO.getAuthstatus();
		switch(status) {
			case 0:
				memberLauchInfoVO.setAuthstatusText("未实名认证");
				break;
			case 1:
				memberLauchInfoVO.setAuthstatusText("实名认证申请中");
				break;
			case 2:
				memberLauchInfoVO.setAuthstatusText("已实名认证");
				break;
			default:
				break;
		}
		return memberLauchInfoVO;
	}

	@Override
	public List<DetailProjectVO> getLaunchProject(Integer memberId) {
		//获取项目详情对象
			List<DetailProjectVO> launchProjectList = projectPOMapper.selectLaunchProjectVO(memberId);
			for (DetailProjectVO launchProject : launchProjectList) {
				
				//设置剩余天数
				String deployDate = launchProject.getDeployDate();
				Date currentDate = new Date();
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				try {
					Date deployDay = format.parse(deployDate);
					
					// 获取当前当前日期的时间戳
					long currentTimeStamp = currentDate.getTime();
					
					// 获取众筹日期的时间戳
					long deployTimeStamp = deployDay.getTime();
					
					// 两个时间戳相减计算当前已经过去的时间
					long pastDays = (currentTimeStamp - deployTimeStamp) / 1000 / 60 / 60 / 24;
					
					// 获取总的众筹天数
					Integer totalDays = launchProject.getDay();
					
					// 使用总的众筹天数减去已经过去的天数得到剩余天数
					Integer lastDay = (int) (totalDays - pastDays);
					if (lastDay<=0) {//若剩余天数<=0则剩余天数为0且众筹状态设为已关闭
						lastDay = 0;
						Integer money = launchProject.getMoney();
						Integer supportMoney = launchProject.getSupportMoney();
						if(money>supportMoney) {//若筹集天数结束，筹集金额小于目标金额，则设置众筹状态为众筹失败
							launchProject.setStatusText("已关闭");
						}else {
							launchProject.setStatusText("众筹成功");
						}
					}
					launchProject.setLastDay(lastDay);
					
				} catch (ParseException e) {
					e.printStackTrace();
				}
				//设置众筹状态
				Integer status = launchProject.getStatus();
				switch(status) {
					case 0:
						launchProject.setStatusText("审核中");
						break;
					case 1:
						launchProject.setStatusText("众筹中");
						break;
					case 2:
						launchProject.setStatusText("众筹成功");
						break;
					case 3:
						launchProject.setStatusText("已关闭");
						break;
					default:
						break;
				}
			}
			
			return launchProjectList;
	}

	@Override
	public List<TypeVO> getProjectTypeList() {
		
		return  typePOMapper.selectProjectTypeList();
	}

	@Override
	public List<TagVO> getProjectTagList() {

		return tagPOMapper.selectProjectTagList();
	}

	@Override
	public DetailProjectVO getDetailProject(Integer projectId) {
		//获取项目详情对象
		DetailProjectVO detailProjectVO = projectPOMapper.selectDetailProject(projectId);
		
		//设置剩余天数
		String deployDate = detailProjectVO.getDeployDate();
		Date currentDate = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date deployDay = format.parse(deployDate);
			
			// 获取当前当前日期的时间戳
			long currentTimeStamp = currentDate.getTime();
			
			// 获取众筹日期的时间戳
			long deployTimeStamp = deployDay.getTime();
			
			// 两个时间戳相减计算当前已经过去的时间
			long pastDays = (currentTimeStamp - deployTimeStamp) / 1000 / 60 / 60 / 24;
			
			// 获取总的众筹天数
			Integer totalDays = detailProjectVO.getDay();
			
			// 使用总的众筹天数减去已经过去的天数得到剩余天数
			Integer lastDay = (int) (totalDays - pastDays);
			if (lastDay<=0) {
				lastDay = 0;
				Integer money = detailProjectVO.getMoney();
				Integer supportMoney = detailProjectVO.getSupportMoney();
				if(money>supportMoney) {//若筹集天数结束，筹集金额小于目标金额，则设置众筹状态为众筹失败
					detailProjectVO.setStatusText("已关闭");
				}else {
					detailProjectVO.setStatusText("众筹成功");
				}
			}
			detailProjectVO.setLastDay(lastDay);
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//设置众筹状态
		Integer status = detailProjectVO.getStatus();
		switch(status) {
			case 0:
				detailProjectVO.setStatusText("审核中");
				break;
			case 1:
				detailProjectVO.setStatusText("众筹中");
				break;
			case 2:
				detailProjectVO.setStatusText("众筹成功");
				break;
			case 3:
				detailProjectVO.setStatusText("已关闭");
				break;
			default:
				break;
		}
		return detailProjectVO;
	}

	//删除我发起的项目,级联删除项目图片、项目标签、项目分类、项目回报，订单项目
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
	@Override
	public void delDetailProject(Integer projectId) {
		projectPOMapper.deleteProjectItemPicByProjectId(projectId);
		projectPOMapper.deleteProjectTagByProjectId(projectId);
		projectPOMapper.deleteProjectTypeByProjectId(projectId);
		projectPOMapper.deleteProjectReturnByProjectId(projectId);
		projectPOMapper.deleteProjectOrderByProjectId(projectId);
		projectPOMapper.deleteByPrimaryKey(projectId);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
	@Override
	public void updateDetailProject(DetailProjectVO detailProjectVO,Integer projectId) {
		Integer day = detailProjectVO.getDay();
		Long money = (long)detailProjectVO.getMoney();
		String projectDesc = detailProjectVO.getProjectDesc();
		String projectName = detailProjectVO.getProjectName();
		ProjectPO projectPO = new ProjectPO();
		projectPO.setId(projectId);
		projectPO.setDay(day);
		projectPO.setMoney(money);
		projectPO.setProjectDescription(projectDesc);
		projectPO.setProjectName(projectName);
		projectPOMapper.updateByPrimaryKeySelective(projectPO);
		
	}

	@Override
	public PageInfo<PortalProjectVO> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
		PageHelper.startPage(pageNum, pageSize);
		List<PortalProjectVO> projectList = projectPOMapper.selectProjectByKeyword(keyword);
		PageInfo<PortalProjectVO> pageInfo = new PageInfo<>(projectList);
		return pageInfo;
	}

	@Override
	public PageInfo<PortalProjectVO> getProjectByTypeIdPageInfo(Integer pageNum, Integer pageSize, String keyword,
			Integer typeId) {
		PageHelper.startPage(pageNum, pageSize);
		List<PortalProjectVO> typeProjectList = projectPOMapper.selectProjectByTypeIdAndKeyword(keyword,typeId);
		PageInfo<PortalProjectVO> pageInfo = new PageInfo<>(typeProjectList);
		return pageInfo;
	}

	@Override
	public PageInfo<PortalProjectVO> getProjectByStatusPageInfo(Integer pageNum, Integer pageSize, String keyword,
			Integer status) {
		PageHelper.startPage(pageNum, pageSize);
		List<PortalProjectVO> statusProjectList = projectPOMapper.selectProjectByStatusAndKeyword(keyword,status);
		PageInfo<PortalProjectVO> pageInfo = new PageInfo<>(statusProjectList);
		return pageInfo;
	}

	@Override
	public PageInfo<PortalProjectVO> getProjectOrderByPageInfo(Integer pageNum, Integer pageSize, String keyword,String factor) {
		PageHelper.startPage(pageNum, pageSize);
		List<PortalProjectVO> orderByProjectList = projectPOMapper.selectProjectOrderByAndKeyword(keyword,factor);
		PageInfo<PortalProjectVO> pageInfo = new PageInfo<>(orderByProjectList);
		return pageInfo;
	}
}
